import React, { useState, useEffect } from 'react';
import { Tree, message, Spin, Empty } from 'antd';
import request from '../../utils/request';
import './DataAreaManagement.css';

// 定义树节点数据类型
interface TreeNodeData {
  task_name: string;
  data_set_list: {
    data_set_name: string;
    key: string;
  }[];
}

// 定义文件数据类型（复用DataAreaResult）
interface FileData {
  id: number;
  user_id: number;
  file_name: string;
  file_path: string;
  create_time: string;
  data_size: number;
  task: string;
  dm_zhname: string;
  data_level: string;
  left_latitude: number;
  left_longitude: number;
  right_latitude: number;
  right_longitude: number;
  // 添加下载所需的必要参数
  product_id: number;
  data_type: string;
}

interface GlobalDataTreeProps {
  planetId: number;
  onFileDataChange: (files: FileData[]) => void;
}

const GlobalDataTree: React.FC<GlobalDataTreeProps> = ({ planetId, onFileDataChange }) => {
  const [treeData, setTreeData] = useState<TreeNodeData[]>([]);
  const [loading, setLoading] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  // 获取树数据
  const fetchTreeData = async () => {
    if (!planetId) return;
    
    setLoading(true);
    try {
      const response = await request.get('/GIS/GISDataAreaTree', {
        params: { planet_id: planetId }
      });

      if (response.data?.code === 200) {
        const data = response.data.data;
        setTreeData(data);
        
        // 默认全展开所有节点
        const allKeys: React.Key[] = [];
        data.forEach((item: TreeNodeData) => {
          // 添加第一级节点（任务）
          allKeys.push(item.task_name);
          // 添加第二级节点（数据集）
          item.data_set_list.forEach((dataset) => {
            allKeys.push(`dataset_${dataset.key}`);
          });
        });
        setExpandedKeys(allKeys);
      }
    } catch (error) {
      console.error('获取树数据失败:', error);
      message.error('获取树数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取文件数据
  const fetchFileData = async (treeUuid: string) => {
    if (!planetId || !treeUuid) return;
    
    setLoading(true);
    try {
      const response = await request.get('/GIS/GISDataAreaFile', {
        params: {
          planet_id: planetId,
          tree_uuid: treeUuid
        }
      });

      if (response.data?.code === 200) {
        const fileData = response.data.data.list;
        onFileDataChange(fileData);
      }
    } catch (error) {
      console.error('获取文件数据失败:', error);
      message.error('获取文件数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理树节点点击
  const handleTreeSelect = (selectedKeys: React.Key[], info: any) => {
    // 如果点击的是第一级节点（任务），用于切换展开/收起
    if (info.node.key && !info.node.key.includes('dataset_')) {
      const isExpanded = expandedKeys.includes(info.node.key);
      if (isExpanded) {
        // 如果已展开，则收起
        setExpandedKeys(expandedKeys.filter(key => key !== info.node.key));
      } else {
        // 如果未展开，则展开
        setExpandedKeys([...expandedKeys, info.node.key]);
      }
      return; // 不设置选中状态
    }
    
    // 如果点击的是第二级节点（数据集），设置选中状态并获取文件数据
    if (info.node.key && info.node.key.includes('dataset_')) {
      setSelectedKeys(selectedKeys);
      const treeUuid = info.node.key.replace('dataset_', '');
      fetchFileData(treeUuid);
    }
  };

  // 处理树节点展开（保留原有功能，但主要用于图标点击）
  const handleTreeExpand = (expandedKeys: React.Key[]) => {
    setExpandedKeys(expandedKeys);
  };

  // 构建树结构数据
  const buildTreeData = () => {
    return treeData.map((task) => ({
      title: (
        <span>
          {task.task_name}
        </span>
      ),
      key: task.task_name,
      className: 'level-1-node',
      children: task.data_set_list.map((dataset) => ({
        title: (
          <span>
            {dataset.data_set_name}
          </span>
        ),
        key: `dataset_${dataset.key}`,
        isLeaf: true,
        className: 'level-2-node',
      })),
    }));
  };

  // 监听planetId变化
  useEffect(() => {
    if (planetId) {
      fetchTreeData();
    }
  }, [planetId]);

  return (
    <div style={{ marginBottom: 16 }}>
      <div className="data-area-tree-container" style={{ display: 'block', padding: 12, maxHeight: '400px', overflow: 'auto' }}>
        <Spin spinning={loading}>
          {treeData.length > 0 ? (
            <Tree
              blockNode
              expandedKeys={expandedKeys}
              selectedKeys={selectedKeys}
              onSelect={handleTreeSelect}
              onExpand={handleTreeExpand}
              treeData={buildTreeData()}
            />
          ) : (
            <Empty description="暂无数据" style={{ padding: '20px 0' }} />
          )}
        </Spin>
      </div>
    </div>
  );
};

export default GlobalDataTree;
